/**
 * 文件名：JwtAuthenticationFilter.java
 * 功能：JWT 认证过滤器
 * 作用：拦截每次 HTTP 请求，从请求头中提取并验证 JWT Token，将用户信息设置到 Spring Security 上下文
 * 模块关系：
 *   - 继承 OncePerRequestFilter：确保每次请求只执行一次
 *   - 依赖 JwtTokenUtil：验证和解析 Token
 *   - 被 SecurityConfig 注册：添加到 Spring Security 过滤器链中
 *   - 与 UserController 协同：保证只有有效 Token 才能访问受保护的接口
 * 作者：白永康
 * 学号：2501210209
 */
package com.example.demo.security;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;

/**
 * JWT 认证过滤器
 * 每次请求都会检查 Authorization 请求头，验证 JWT Token 并设置认证信息
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtTokenUtil jwtTokenUtil;

    /**
     * 构造函数，注入 JwtTokenUtil 依赖
     * @param jwtTokenUtil JWT 工具类
     */
    public JwtAuthenticationFilter(JwtTokenUtil jwtTokenUtil) {
        this.jwtTokenUtil = jwtTokenUtil;
    }

    /**
     * 过滤器核心逻辑：验证 JWT Token 并设置认证上下文
     * @param request HTTP 请求
     * @param response HTTP 响应
     * @param filterChain 过滤器链
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, 
                                    HttpServletResponse response, 
                                    FilterChain filterChain) throws ServletException, IOException {
        
        String header = request.getHeader("Authorization");
        
        if (header != null && header.startsWith("Bearer ")) {
            String token = header.substring(7);
            
            if (jwtTokenUtil.validateToken(token)) {
                Long userId = jwtTokenUtil.getUserIdFromToken(token);
                String username = jwtTokenUtil.getUsernameFromToken(token);
                
                UsernamePasswordAuthenticationToken authentication = 
                    new UsernamePasswordAuthenticationToken(userId, null, new ArrayList<>());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        
        filterChain.doFilter(request, response);
    }
}
